<?php

class LeagueController extends Zend_Controller_Action{
	public function init(){
		
		$this->oLoggedInUser = Default_Service_Auth::getLoggedInUser();

		
	}
	
	// function show the leagues available
	public function indexAction(){
		
		$criteria = new Criteria();
		$criteria->add(LeaguePeer::IS_ACTIVE, 'Y');
		$oLeagues = LeaguePeer::doSelect($criteria);
		
		if(isset($this->oLoggedInUser))
		{
			$id = $this->oLoggedInUser->getId();
			
			$criteria = new Criteria();
			$criteria->add(UserTeamPeer::USER_ID,$id,Criteria::EQUAL);
			$userTeamRes = UserTeamPeer::doSelect($criteria);
			
			$teamId = "";
			if(count($userTeamRes) > 0)
			{
				foreach($userTeamRes as $userTeamRes)
				{
					$userTeamRes->getId();
					$teamId[] = $userTeamRes->getId();
				}
			}
			
			$this->view->teamId = $teamId;		
		    $this->view->LoggedUserId = $this->oLoggedInUser->getId();
		    
		}
		$this->view->leagues = $oLeagues;
		
	}
	
	// function to create the league
	
	public function createAction(){
		if(!isset($this->oLoggedInUser)){
			$this->_helper->redirector("index","login","default", array("test" => 'te'));
		}
		
		$request = $this->getRequest();
		
		if($request->isPost()){
			
			$leagueName = $request->getPost('league_name');
			$tournament = $request->getPost('tournament');
			$isPublic	= $request->getPost('status_type');
			
				//check wheteher league name exists or not
				if(!LeaguePeer::isAlreadyExists($leagueName))
				{
				try{
					// now save the data
					$league = new League();
					$league->setName($leagueName)
						   ->setOwnerId($this->oLoggedInUser->getId())	
							->setTournamentId($tournament)
							->setIsPublic($isPublic)
							->setAddedDate(date('Y-m-d'))
							->save();
							
				
							
					//@todo post to FB the user uses facebook		
					// i will add my code here
					
							
					// go to the next step
					$this->_helper->_redirector("invite", "league", "default", array("id" => $league->getId()));	
					
					
				}catch(Exception $e){
					
				}
				}
				else 
				{
					echo "league name already exits";
				}
			
				
		
		}
		
		$criteria = new Criteria();
		$criteria->add(TournamentPeer::IS_ACTIVE, 'Y');
		$tournaments = TournamentPeer::doSelect($criteria);
	
		$this->view->tournaments = $tournaments;
	}
	
	// function to invite the friends
	public function inviteAction(){
		if(!isset($this->oLoggedInUser)){
			$this->_helper->redirector("index","login","default");
		}
		
		$id = $this->_getParam("id");
		
		//code to get 
		$criteria = new Criteria();
		$criteria->add(LeaguePeer::ID,$id,Criteria::EQUAL);
		$criteria->add(LeaguePeer::IS_PUBLIC,'Y',Criteria::EQUAL);
		$leagueRes = LeaguePeer::doCount($criteria);
		
		
		$request = $this->getRequest();
		
		if($request->isPost())
		{
			
			
			if($leagueRes > 0)
			{
			
				$emailAddress = explode(",", $request->getPost('invite'));				
				if(is_array($emailAddress))
				{
						
						for($i=0;$i<count($emailAddress);$i++)
						{
							$oInvitation = new LeagueInvitation();
							$oInvitation->setLeagueId($id)
										->setEmail($emailAddress[$i])
										->setInvitationDate(date('Y-m-d'))
										->save();
							
						}
						
				}
				
				array_unique($emailAddress);
				$mailDetails = array(
	
												"to"				=>	$emailAddress,
												"subject"			=>	"Join Cric World",
												"leagueid"			=>  $id,
												
												
											);
	
						$oMail = new Default_Service_Mail();
						$oMail->sendMail("publicjoin", $mailDetails);
	
						$this->view->info = array(
	                                                    "type"		=>  "success",
	                                                    "message"	=>	Default_Service_Message::MAIL_SENT_SUCCESSFULLY
	                    );
				
				$this->view->message = "Invitation(s) have been sent successfully";	
				
			}
			else 
			{
				
		    	$emailAddress = explode(",", $request->getPost('invite'));	
				if(is_array($emailAddress))
				{
											
						for($i=0;$i<count($emailAddress);$i++)
						{
							$accesscode = Default_Service_Auth::accessCode();	
							$oInvitation = new LeagueInvitation();
							$oInvitation->setLeagueId($id)
										->setEmail($emailAddress[$i])
										->setAccessCode($accesscode)
										->setInvitationDate(date('Y-m-d'))
										->save();
										
							//code to sent access code for email address
							$mailDetails = array(
				
															"to"				=>	$emailAddress[$i],
															"subject"			=>	"Access Code to Join League",
															"code"				=>  $accesscode,
															"leagueid"			=>  $id,
															
														);
				
									$oMail = new Default_Service_Mail();
									$oMail->sendMail("privatejoin", $mailDetails);
				
									$this->view->info = array(
				                                                    "type"		=>  "success",
				                                                    "message"	=>	Default_Service_Message::MAIL_SENT_SUCCESSFULLY
				                    );	
				               $this->view->message = "Invitation(s) have been sent successfully.";	     		
						}
				}		
				
				
			}
		}
		
		$this->view->leagueId = $id;
	}
	
	/**
	 * Function to make the user join the league 
	 * 
	 * Enter description here ...
	 */
	public function joinAction(){
		if(!isset($this->oLoggedInUser))
		{
			 $_SESSION['redirect_url'] = $this->getRequest()->getRequestUri(); // storing url when a user login through onclick of url in eamil			
			 $this->_helper->redirector("index","login","default");
		}
		
		$id = $this->_getParam("id"); // get the league id and corresponding object
		$oLeague = LeaguePeer::retrieveByPK($id);
		$leagueName = $oLeague->getName();
		
		$this->view->leagueName = $leagueName;
		$this->view->tid = $oLeague->getTournamentId();
		$this->view->userId = $this->oLoggedInUser->getId();
		$this->view->id = $id;
		
		if($oLeague){
			
			if($oLeague->getIsPublic() == "Y"){
				$request = $this->getRequest();
				if($request->isPost())
				{
					$userID = $this->oLoggedInUser->getId();
					$criteria = new Criteria();
					$criteria->add(UserTeamPeer::USER_ID,$userID,Criteria::EQUAL);
					$oUserTeam = UserTeamPeer::doSelectOne($criteria);
					
					 $oLeagueTeam = new LeagueTeam();
					 $oLeagueTeam->setLeagueId($id)
					 			 ->setTeamId($oUserTeam->getId())
					 			 ->setJoinedDate(date('Y-m-d'))
					 			 ->save();
					 //code to get username from user table			 
					 $oUser = UserPeer::retrieveByPK($userID);
					 $userEmail = $oUser->getUsername(); 
					 
					 //code to get information of logged in user from league invitation table 			 
					 $criteria = new Criteria();
					 $criteria->add(LeagueInvitationPeer::LEAGUE_ID,$id,Criteria::EQUAL);
					 $criteria->add(LeagueInvitationPeer::EMAIL,$userEmail,Criteria::EQUAL);
					 $invitationRes = LeagueInvitationPeer::doSelectOne($criteria);
					
					 if( count($invitationRes) > 0 )
					 {
						 $oLeagueInvitation = LeagueInvitationPeer::retrieveByPK($invitationRes->getId());
						 $oLeagueInvitation->setAcceptedDate(date('Y-m-d'))
						 				   ->setIsAccepted('Y')
						 				   ->save();
					 }

					 
					 $this->view->message = "You have joined successfully.";			 
				}
				//@todo public league..get the username from the logged in user and join direct
				
			}else{
					$request = $this->getRequest();
					if($request->isPost())
					{
						$code = $request->getPost('accesscode');
						
						$criteria = new criteria();
						$criteria->add(LeagueInvitationPeer::LEAGUE_ID,$id,Criteria::EQUAL);
						$criteria->add(LeagueInvitationPeer::ACCESS_CODE,$code,Criteria::EQUAL);
						$codeRes = LeagueInvitationPeer::doCount($criteria);
						if($codeRes > 0)
						{
							$userID = $this->oLoggedInUser->getId();
							$criteria = new Criteria();
							$criteria->add(UserTeamPeer::USER_ID,$userID,Criteria::EQUAL);
							$oUserTeam = UserTeamPeer::doSelectOne($criteria);
							
							 $oLeagueTeam = new LeagueTeam();
							 $oLeagueTeam->setLeagueId($id)
							 			 ->setTeamId($oUserTeam->getId())
							 			 ->setJoinedDate(date('Y-m-d'))
							 			 ->save();
							 $oUser = UserPeer::retrieveByPK($userID);
							 
							$userEmail = $oUser->getUsername(); 
							
							  
							 $invCriteria = new Criteria();
							 $invCriteria->add(LeagueInvitationPeer::LEAGUE_ID,$id,Criteria::EQUAL);
							 $invCriteria->add(LeagueInvitationPeer::EMAIL,$userEmail,Criteria::EQUAL);
							 $invCriteria->add(LeagueInvitationPeer::ACCESS_CODE,$code,Criteria::EQUAL);
							 $oInvitation = LeagueInvitationPeer::doSelectOne($invCriteria);
							 
							if(count($oInvitation) >0)
							{ 
								 $oLeagueInvitation = LeagueInvitationPeer::retrieveByPK($oInvitation->getId());
								 $oLeagueInvitation->setAcceptedDate(date('Y-m-d'))
						 				   ->setIsAccepted('Y')
						 				   ->save();			 
							}			 
							 $this->view->message = "You have joined successfully.";			 
						}
						else 
						{
							echo "Your access code is not correct. Please try entering again...";
							
						}
						
						
						
					}
				//@todo ask for the unique code and then make the user join
			}
			
			
			
		}
		
	}
	
	//function to request for join through admin
	public function requestjoinAction()
	{
		$id = $this->_getParam("id"); // get the league id 
		
		//code to get owner of the league
		$oLeague = LeaguePeer::retrieveByPK($id);
		$ownerId = $oLeague->getOwnerId();
		
		$criteria = new criteria();
		$criteria->add(UserPeer::ID,$ownerId,Criteria::EQUAL);
		$userRes = UserPeer::doSelectOne($criteria);
		
		$username = $userRes->getUsername();
		
		// code to get logged in user details
		$userID = $this->oLoggedInUser->getId();
		$criteria = new Criteria();
		$criteria->add(UserPeer::ID,$userID,Criteria::EQUAL);
		$oUser = UserPeer::doSelectOne($criteria);
		$loggedUser = $oUser->getUsername();
		
		   //code to send mail to admin when a user request for join in leagues
			$mailDetails = array(

											"to"				=>	$username,
											"subject"			=>	"Request from user to join in league.",
											"leagueOwner"       =>  $username,
											"loggeduser"		=>  $loggedUser,
											
											
										);

					$oMail = new Default_Service_Mail();
					$oMail->sendMail("requestjoin", $mailDetails);

					$this->view->info = array(
                                                    "type"		=>  "success",
                                                    "message"	=>	Default_Service_Message::MAIL_SENT_SUCCESSFULLY
                    );	
                    $this->view->message = "Thanks for showing interest in joining league. Mail will be sent regarding your activation code to join in this league.";
	}
	//function to check duplicate of league name
	public function checkleagueAction()
	{
		$this->_helper->viewRenderer->setNoRender(TRUE);
		$this->_helper->layout()->disableLayout();
		$name = $this->_getParam('name');
		
		$criteria = new Criteria();
		$criteria->add(LeaguePeer::NAME,$name,Criteria::EQUAL);
		$count = LeaguePeer::doCount($criteria);
		
		if($count>0)
		{
			echo "League name already exists";
		}
		
	}
	//function to check duplicate of loggedin emai Id while sending invitations
	public function checkemailAction()
	{
	    $this->_helper->viewRenderer->setNoRender(TRUE);
		$this->_helper->layout()->disableLayout();
		$name = $this->_getParam('name');
		$email = explode(",",$name);
		array_unique($email);
		
		$userID = $this->oLoggedInUser->getId();
		$criteria = new Criteria();
		$criteria->add(UserPeer::ID,$userID,Criteria::EQUAL);
		$userRes = UserPeer::doSelectOne($criteria);
		
		$userEmail = $userRes->getUsername();
		for($i=0;$i<count($email);$i++)
		{
			if( $email[$i] == $userEmail )
			{
				echo "You should not enter your email address as you are the owner of league.";
			}
		}
			
	}
	//function to view league information 
	public function viewAction()
	{
		$id = $this->_getParam('id');
		
		$oLeague = LeaguePeer::retrieveByPK($id);
		
		$name = $oLeague->getName();
		$isPublic = $oLeague->getIsPublic();
		$ownerId = $oLeague->getOwnerId();
		$criteria = new Criteria();
		$criteria->add(UserPeer::ID,$ownerId,Criteria::EQUAL);
		$result = UserPeer::doSelectOne($criteria);
		
		$ownerName = $result->getScreenName();
		$createdDate = $oLeague->getAddedDate();
		
		$this->view->id = $id;
		$this->view->name = $name;
		$this->view->ownerName = $ownerName;
		$this->view->date = $createdDate;
		$this->view->ststus = $isPublic;
	}
	
	
}